package com.wechar_rpa.service;

import com.wechar_rpa.model.SubscriptionPlan;
import com.wechar_rpa.model.User;
import com.wechar_rpa.model.UserSubscription;
import com.wechar_rpa.repository.SubscriptionPlanRepository;
import com.wechar_rpa.repository.UserSubscriptionRepository;
import com.wechar_rpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SubscriptionService {

    @Autowired
    private SubscriptionPlanRepository planRepository;

    @Autowired
    private UserSubscriptionRepository subscriptionRepository;

    @Autowired
    private UserRepository userRepository;

    public SubscriptionPlan getPlanByLevel(int level) {
        return planRepository.findByLevel(level).orElse(null);
    }

    public UserSubscription getUserSubscription(String username) {
        return subscriptionRepository.findByUser_Username(username).orElse(null);
    }

    public void subscribeUser(String username, int planLevel) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isEmpty()) return;

        SubscriptionPlan plan = getPlanByLevel(planLevel);
        if (plan == null) return;

        UserSubscription subscription = new UserSubscription();
        subscription.setUser(userOpt.get());
        subscription.setPlan(plan);
        subscription.setSubscribedAt(new Date());
        subscription.setExpiresAt(calculateExpiryDate(planLevel));
        subscription.setIsActive(true);

        subscriptionRepository.save(subscription);
    }

    private Date calculateExpiryDate(int planLevel) {
        // 简单实现：按月订阅，30天有效期
        return new Date(System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000);
    }
}